package service

import (
	"context"
	"fx_swift_forex/api"
	"fx_swift_forex/internal/model"
	"fx_swift_forex/pkg/code"
	"fx_swift_forex/pkg/global"
	"fx_swift_forex/pkg/internalerrors"
	"fx_swift_forex/pkg/logger"
	"github.com/gogf/gf/v2/container/gvar"
	"github.com/gogf/gf/v2/frame/g"
	"regexp"
)

// 从缓存中获取CC银行请求token
func GetCCTokenToRedis(ctx context.Context) (string, error) {
	var (
		err         error
		redisResult *gvar.Var
		redisToken  string
	)
	redisResult, err = g.Redis().Get(ctx, global.ViperObj.GetString("forex.loginId"))
	if err != nil || redisResult.Val() == nil {
		redisToken, err = GetCurrencyCloudToken(ctx)
		if err != nil {
			return "", err
		}
	} else {
		redisToken = redisResult.String()
	}
	return redisToken, err
}

// 获取国家信息
func GetForexCountryInfo(ctx context.Context) ([]*api.GetCountryRes, error) {
	var (
		err         error
		countryList []*model.ForexCountry
	)
	if err = global.GFDB.Schema("forex").Model("forex_country").OrderDesc("chinese_name").Scan(&countryList); err != nil {
		logger.SugarLogger.Error(err)
		return nil, internalerrors.New(code.ErrUnknown, "数据查询异常")
	}
	result := make([]*api.GetCountryRes, 0)
	for _, value := range countryList {
		result = append(result, &api.GetCountryRes{
			Id: value.ID,
			NameInfo: api.NameInfo{
				ChineseName: value.ChineseName,
				EnglishName: value.EnglishName,
			},
			CountryCode:    value.CountryCode,
			IsoCountryCode: value.IsoCountryCode,
			Status:         value.Status,
		})
	}
	return result, err
}

func VerifyEmailFormat(email string) bool {
	pattern := `\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*` //匹配电子邮箱
	reg := regexp.MustCompile(pattern)
	return reg.MatchString(email)
}

func GetProvinceInfo(ctx context.Context) ([]*api.ProvinceRes, error) {
	var (
		err         error
		provinceObj []*api.ProvinceRes
	)
	if err = global.GFDB.Model("forex_province_city_base").Fields("country_subdivision").Distinct().Scan(&provinceObj); err != nil {
		logger.SugarLogger.Error(err)
		return nil, internalerrors.New(code.ErrUnknown, "数据查询异常")
	}
	result := make([]*api.ProvinceRes, 0)
	for _, value := range provinceObj {
		result = append(result, &api.ProvinceRes{
			CountrySubdivision: value.CountrySubdivision,
		})
	}
	return result, err
}

func GetCityInfo(ctx context.Context, countrySubdivision string) ([]*api.CityRes, error) {
	var (
		err     error
		cityObj []*api.CityRes
	)

	if err = global.GFDB.Model("forex_province_city_base").Fields("town_name").Where("country_subdivision=?", countrySubdivision).Scan(&cityObj); err != nil {
		logger.SugarLogger.Error(err)
		return nil, internalerrors.New(code.ErrUnknown, "数据查询异常")
	}
	result := make([]*api.CityRes, 0)
	for _, value := range cityObj {
		result = append(result, &api.CityRes{
			TownName: value.TownName,
		})
	}
	return result, err
}

// 从redis读取comply平台的accessToken
func GetComplyTokenToRedis(ctx context.Context) (string, error) {
	var (
		err         error
		redisResult *gvar.Var
		accessToken string
	)

	redisResult, err = g.Redis().Get(ctx, global.ViperObj.GetString("comply.tokenFlag")+global.ViperObj.GetString("comply.userName"))
	if err != nil || redisResult.Val() == nil {
		accessToken, err = GetComplyToken(ctx)
		accessToken = "Bearer " + accessToken
		if err != nil {
			return "", internalerrors.New(code.ErrUnknown, err.Error())
		}
	} else {
		accessToken = redisResult.String()
	}
	return accessToken, err
}

// 从redis获取customerId
func GetRedisCustomerId(ctx context.Context) (string, error) {
	var (
		err             error
		redisCustomerId *gvar.Var
		account         string
		customerId      string
	)
	account = ctx.Value("Account").(string)
	redisCustomerId, err = g.Redis().Get(ctx, account+"_customerId")
	if err != nil || redisCustomerId.Val() == nil {
		customerId = ""
	} else {
		customerId = redisCustomerId.String()
	}

	return customerId, err
}

// 获取公司类型
func GetCompanyType(ctx context.Context) ([]*api.CompanyTypeRes, error) {
	var (
		err            error
		companyTypeObj []*api.CompanyTypeRes
	)

	if err = global.GFDB.Schema("forex").Ctx(ctx).Model("forex_company_type_base").Scan(&companyTypeObj); err != nil {
		logger.SugarLogger.Error(err)
		return nil, internalerrors.New(code.ErrUnknown, "查询数据报错")
	}
	if companyTypeObj == nil {
		return []*api.CompanyTypeRes{}, nil
	}
	return companyTypeObj, err
}

// 获取公司类型
func GetBusinessType(ctx context.Context) ([]*api.BusinessTypeRes, error) {
	var (
		err             error
		businessTypeObj []*api.BusinessTypeRes
	)

	if err = global.GFDB.Schema("forex").Ctx(ctx).Model("forex_business_type_base").Scan(&businessTypeObj); err != nil {
		logger.SugarLogger.Error(err)
		return nil, internalerrors.New(code.ErrUnknown, "查询数据报错")
	}
	if businessTypeObj == nil {
		return []*api.BusinessTypeRes{}, nil
	}
	return businessTypeObj, err
}

// 获取省州二字码
func GetStateOrProvinceInfo(ctx context.Context, isoCountryCode string) ([]*api.GetStateOrProvinceRes, error) {
	var (
		err          error
		provinceList []*model.ForexStateOrProvince
	)
	if isoCountryCode == "" {
		return nil, internalerrors.New(code.ErrUnknown, "国家不能为空")
	}
	if err = global.GFDB.Schema("forex").Model("forex_state_or_province_base").Where("iso_country_code=?", isoCountryCode).OrderAsc("state_or_province_code").Scan(&provinceList); err != nil {
		logger.SugarLogger.Error(err)
		return nil, internalerrors.New(code.ErrUnknown, "数据查询异常")
	}
	result := make([]*api.GetStateOrProvinceRes, 0)
	for _, value := range provinceList {
		result = append(result, &api.GetStateOrProvinceRes{
			Id: value.ID,
			NameInfo: api.NameInfo{
				ChineseName: value.ChineseName,
				EnglishName: value.EnglishName,
			},
			IsoCountryCode:      value.IsoCountryCode,
			StateOrProvinceCode: value.StateOrProvinceCode,
		})
	}
	return result, err
}
